package net.tools;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public final class BeansHelp {
	private static Logger log = Logger.getLogger(BeansHelp.class);
	private static ApplicationContext ctx;
	private static WebApplicationContext webCtx;

	protected BeansHelp() {
	}

	static {

		if (ctx == null) {
            try{
			webCtx = WebApplicationContextUtils
					.getRequiredWebApplicationContext(ServletActionContext
							.getServletContext());
                log.info("从web.xml容器中加载spring-config.xml");
            }catch(Exception e){
                log.info("直接加载spring-config.xml");
            }
			if (webCtx == null)
				ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		}
	}


	/**
	 * 通过beanID获取bean实例
	 * 
	 * @param beanID
	 *            bean的代码
	 * @return 返回对应的实例
	 *             bean没有定义
	 */
	public static Object getBeanInstance(String beanID)
			throws RuntimeException {
	//	log.info("在spring容器中获取Bean对象 ID=" + beanID);
		Object obj;
		if (BeansHelp.ctx == null) {
			if (BeansHelp.webCtx.containsBeanDefinition(beanID)) {
				obj = BeansHelp.webCtx.getBean(beanID);
			} else {
				log.info("beanID=" + beanID + "没有定义");
				throw new RuntimeException(beanID + "没有定义!");
			}
		} else {
			if (BeansHelp.ctx.containsBeanDefinition(beanID)) {
				obj = BeansHelp.ctx.getBean(beanID);
			} else {
				log.info("beanID=" + beanID + "没有定义");
				throw new RuntimeException(beanID + "没有定义!");
			}
		}
		// if (BeansHelp.ctx.containsBeanDefinition(beanID)) {
		// obj = BeansHelp.ctx.getBean(beanID);
		// } else {
		// log.info("beanID=" + beanID + "没有定义");
		// throw new NoSuchBeanException(beanID + "没有定义!");
		// }
		return obj;
	}
}
